﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.Framework;
using System.Reflection;
using WorldClock.BO;

namespace WorldClock
{
    public partial class MainControl : IMagnet, IFlip, IRequiresStorage
    {
        private WorldTimeViewModel _worldTimeViewModelDataSource;
        private ClockConfig _clockConfig;
        private Storage _storage;
        private string _clockConfigFilePath;


        /// <summary>
        /// Constructor
        /// </summary>
        public MainControl()
        {
            this.InitializeComponent();
            _configBt.Click += new RoutedEventHandler(ConfigBt_Click);
            _saveBt.Click += new RoutedEventHandler(SaveBt_Click);
            _customCityNameTbx.KeyUp += new KeyEventHandler(CustomCityNameTbx_KeyUp);
            _worldTimeViewModelDataSource = this.Resources["WorldTimeViewModelDataSource"] as WorldTimeViewModel;
            Connector.MagnetDropped += new Connector.MagnetDroppedHandler(Connector_MagnetDropped);
        }

        void Connector_MagnetDropped(IMagnet droppedMagnet)
        {
            _worldTimeViewModelDataSource.Init();
            if (droppedMagnet == this)
                SelectTimeZoneFromId(_clockConfig.TimeZoneInfoId);
        }

        void CustomCityNameTbx_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Keyboard.Focus(_saveBt);
                SaveBt_Click(sender, e);
            }
        }

        void SaveBt_Click(object sender, RoutedEventArgs e)
        {
            SaveState();
            if (FlipRequested != null)
                FlipRequested(MagnetSides.Front);
        }

        void ConfigBt_Click(object sender, RoutedEventArgs e)
        {
            if (FlipRequested != null)
                FlipRequested(MagnetSides.Back);
        }

        void SelectTimeZoneFromId(string timeZoneId)
        {
            foreach (TimeZoneInfoViewModel tz in _timeZonesLbx.Items)
            {
                if (tz.Id == timeZoneId)
                {
                    if (!string.IsNullOrEmpty(_clockConfig.CityName))
                        tz.ShortName = _clockConfig.CityName;

                    _timeZonesLbx.SelectedItem = tz;
                    SaveState();
                    break;
                }
            }
        }

        #region IMagnet Members

        /// <summary>
        /// This is your magnet name, it will be used in the magnets explorer.
        /// </summary>
        public string MagnetName
        {
            get
            {
                return "World Clock";
            }
        }

        /// <summary>
        /// You MUST specify a StoreID, it has to be unique for each magnet.
        /// Use "Tools" -> "Create GUID" -> "Registry Format" -> "Copy" to create a StoreID for your magnet
        /// </summary>
        public string StoreID
        {
            get
            {
                return "{7D8A89C2-D2FD-4e4b-A363-12D8F3DB5586}";
            }
        }

        /// <summary>
        /// myBoard will call this method when your magnet is about to be destroyed.
        /// Add all cleaning code here.
        /// </summary>
        public void Terminate()
        {
            _worldTimeViewModelDataSource.Stop();
            Connector.MagnetDropped -= new Connector.MagnetDroppedHandler(Connector_MagnetDropped);
            GC.Collect();
        }

        /// <summary>
        /// This should return the image you want to use for your magnet in the magnet explorer
        /// </summary>
        public BitmapImage Icon
        {
            get
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                return ResourcesAccess.GetBitmapImageFromResource(asm, "WorldClock.Images.icon.png");
            }
        }

        /// <summary>
        /// This should return the image you want your magnet morphs into when the user drag it out of the magnet explorer.
        /// </summary>
        public BitmapImage Thumbnail
        {
            get
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                return ResourcesAccess.GetBitmapImageFromResource(asm, "WorldClock.Images.thumb.png");
            }
        }

        #endregion

        #region IFlip Members

        public event OnFlipRequested FlipRequested;

        public Panel GetBackSide()
        {
            return _back;
        }

        public Panel GetFrontSide()
        {
            return _front;
        }

        #endregion

        #region IRequiresStorage Members

        public void GetStorage(Storage storage)
        {
            _storage = storage;
            _clockConfigFilePath = System.IO.Path.Combine(_storage.StorageDirectory.FullName,"Settings.xml");
            _clockConfig = Serializer.Load<ClockConfig>(MagnetName, _clockConfigFilePath);
            if (string.IsNullOrEmpty(_clockConfig.TimeZoneInfoId))
                _clockConfig.TimeZoneInfoId = TimeZoneInfo.Local.Id;                
        }

        public void SaveState()
        {
            TimeZoneInfoViewModel tzivm = _timeZonesLbx.SelectedItem as TimeZoneInfoViewModel;
            if (tzivm != null)
            {
                _clockConfig.CityName = tzivm.ShortName;
                _clockConfig.TimeZoneInfoId = tzivm.Id;
                Serializer.Save<ClockConfig>(MagnetName, _clockConfig, _clockConfigFilePath);
            }
        }

        #endregion
    }
}